// import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amap_flutter_location_ohos/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:amap_flutter_location_ohos/amap_flutter_location_ohos.dart';
import 'package:permission_handler_ohos/permission_handler_ohos.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'show_map_page.dart';

void main() {
  runApp(MaterialApp(
    home: const MyApp(),
    debugShowCheckedModeBanner: false,
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  StreamSubscription<Map<String, Object>>? _locationListener;
  Map<String, Object>? _locationResult;
  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  @override
  void initState() {
    super.initState();
    // 同意隐私政策
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey("1dbf56e2e8a4d0e4cdc2df9efd36bc71",
        "dfb64c0463cb53927914364b5c09aba0", "2e36edc989da10f1010af27ba2ec3557");

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationResult = result;
      });
    });
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = false;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    ///设置Android端的定位模式<br>
    ///可选值：<br>
    ///<li>[AMapLocationMode.Battery_Saving]</li>
    ///<li>[AMapLocationMode.Device_Sensors]</li>
    ///<li>[AMapLocationMode.Hight_Accuracy]</li>
    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    ///设置iOS端期望的定位精度
    /// 可选值：<br>
    /// <li>[DesiredAccuracy.Best] 最高精度</li>
    /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
    /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
    /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
    /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
    locationOption.desiredAccuracy = DesiredAccuracy.Best;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);
  }

  ///开始定位
  void _startLocation() {
    ///开始定位之前设置定位参数
    _setLocationOption();
    _locationPlugin.startLocation();
  }

  ///停止定位
  void _stopLocation() {
    _locationPlugin.stopLocation();
  }

  void _showMapPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const ShowMapPage()),
    );
  }

  @override
  void dispose() {
    super.dispose();

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener?.cancel();
    }

    ///销毁定位
    _locationPlugin.destroy();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> widgets = <Widget>[];

    if (_locationResult != null) {
      _locationResult?.forEach((key, value) {
        widgets.add(_resultWidget(key, value));
      });
    }

    widgets.addAll([
      TextButton(
          onPressed: () async {
            final PermissionStatusOhos status =
                await PermissionHandlerOhos.checkPermissionStatus(
                    PermissionOhos.location.name);
            if (status == PermissionStatusOhos.granted) {
              Fluttertoast.showToast(msg: "已申请");
            } else {
              Fluttertoast.showToast(msg: "未申请");
            }
          },
          child: const Text("检查权限")),
      TextButton(
          onPressed: () {
            PermissionHandlerOhos.requestPermissions([
              'ohos.permission.APPROXIMATELY_LOCATION',
              'ohos.permission.LOCATION',
            ]).then((value) async {
              if ((await PermissionHandlerOhos.checkPermissionStatus(
                      PermissionOhos.location.name)) ==
                  PermissionStatusOhos.granted) {
                Fluttertoast.showToast(msg: "已申请");
              } else {
                Fluttertoast.showToast(msg: "未申请");
              }
            });
          },
          child: const Text("申请权限")),
      TextButton(onPressed: () => _startLocation(), child: Text("获取位置")),
      TextButton(onPressed: () => _stopLocation(), child: Text("停止获取位置")),
      TextButton(onPressed: () => _showMapPage(), child: Text("显示地图")),
    ]);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AMap Plugin Example App'),
        ),
        body: Column(children: widgets),
      ),
    );
  }

  Widget _resultWidget(key, value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          alignment: Alignment.centerRight,
          width: 100.0,
          child: Text('$key :'),
        ),
        Container(width: 5.0),
        Flexible(child: Text('$value', softWrap: true)),
      ],
    );
  }
}
